const { prisma } = require('../config/prisma');
const { workingTimeHelper } = require('../utils/workingTime');
const ListingPrisma = require('../models/ListingPrisma');

/**
 * 测试自动发布功能
 * 创建一个休息时间发布的测试数据，并验证自动发布机制
 */
async function testAutoPublishFeature() {
  console.log('=== 测试自动发布功能 ===\n');

  try {
    // 1. 创建一个测试用的挂牌信息，模拟休息时间发布
    console.log('1. 创建测试数据（模拟休息时间发布）');
    
    // 设置自动发布时间为1分钟前（模拟超时）
    const autoPublishTime = new Date();
    autoPublishTime.setMinutes(autoPublishTime.getMinutes() - 1);
    
    const testListing = await prisma.listings.create({
      data: {
        user_id: 4, // 使用现有用户
        listing_type: 'COMPANY',
        company_name: '测试自动发布公司',
        status: 'OFF_SHELF', // 待审核状态下先下架
        is_negotiable: true,
        registration_province: '江苏省',
        registration_city: '苏州市',
        establishment_date: new Date('2024-01-01'),
        registered_capital_range: 'FROM_500K_TO_1M', // 50-100万
        audit_status: 'PENDING',
        auto_publish_at: autoPublishTime // 设置为1分钟前，模拟超时
      }
    });
    
    console.log(`创建测试数据成功: ${testListing.company_name} (ID: ${testListing.id})`);
    console.log(`自动发布时间: ${autoPublishTime.toLocaleString('zh-CN')}`);
    console.log(`当前时间: ${new Date().toLocaleString('zh-CN')}`);
    console.log('该信息应该被自动发布\n');

    // 2. 检查超时的待审核信息
    console.log('2. 检查超时的待审核信息');
    const now = new Date();
    const expiredListings = await prisma.listings.findMany({
      where: {
        audit_status: 'PENDING',
        auto_publish_at: {
          lte: now
        }
      },
      include: {
        users: true
      }
    });
    
    console.log(`发现 ${expiredListings.length} 条超时待发布的信息:`);
    expiredListings.forEach((listing, index) => {
      console.log(`  ${index + 1}. ${listing.company_name} - 自动发布时间: ${listing.auto_publish_at?.toLocaleString('zh-CN')}`);
    });
    console.log();

    // 3. 执行自动发布
    console.log('3. 执行自动发布');
    const publishedCount = await ListingPrisma.autoPublishExpired();
    console.log(`成功自动发布 ${publishedCount} 条信息\n`);

    // 4. 验证自动发布结果
    console.log('4. 验证自动发布结果');
    const updatedListing = await prisma.listings.findUnique({
      where: { id: testListing.id },
      include: {
        users: true,
        administrators: true
      }
    });
    
    if (updatedListing) {
      console.log(`测试信息状态更新:`);
      console.log(`  公司名称: ${updatedListing.company_name}`);
      console.log(`  审核状态: ${updatedListing.audit_status}`);
      console.log(`  信息状态: ${updatedListing.status}`);
      console.log(`  审核时间: ${updatedListing.audit_time?.toLocaleString('zh-CN')}`);
      console.log(`  审核备注: ${updatedListing.audit_comment}`);
      
      if (updatedListing.audit_status === 'APPROVED' && updatedListing.status === 'ON_SALE') {
        console.log('✅ 自动发布成功！');
      } else {
        console.log('❌ 自动发布失败');
      }
    }
    console.log();

    // 5. 检查审核统计
    console.log('5. 检查审核统计');
    const [pending, approved, rejected] = await Promise.all([
      prisma.listings.count({ where: { audit_status: 'PENDING' } }),
      prisma.listings.count({ where: { audit_status: 'APPROVED' } }),
      prisma.listings.count({ where: { audit_status: 'REJECTED' } })
    ]);
    
    console.log(`当前审核统计:`);
    console.log(`  待审核: ${pending}`);
    console.log(`  已通过: ${approved}`);
    console.log(`  已拒绝: ${rejected}`);
    console.log(`  总计: ${pending + approved + rejected}\n`);

    // 6. 清理测试数据
    console.log('6. 清理测试数据');
    await prisma.listings.delete({
      where: { id: testListing.id }
    });
    console.log('测试数据清理完成\n');

    console.log('=== 自动发布功能测试完成 ===');
    console.log('\n测试结果总结:');
    console.log('✅ 创建休息时间发布的测试数据');
    console.log('✅ 检查超时待审核信息');
    console.log('✅ 执行自动发布逻辑');
    console.log('✅ 验证自动发布结果');
    console.log('✅ 更新审核统计');
    console.log('✅ 清理测试数据');

  } catch (error) {
    console.error('测试过程中发生错误:', error);
  } finally {
    await prisma.$disconnect();
  }
}

// 运行测试
if (require.main === module) {
  testAutoPublishFeature().then(() => {
    console.log('\n测试完成');
    process.exit(0);
  }).catch(error => {
    console.error('测试失败:', error);
    process.exit(1);
  });
}

module.exports = { testAutoPublishFeature };
